package com.jshongli.myapplication.task;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jshongli.myapplication.R;
import com.jshongli.myapplication.base.BaseActivity;
import com.jshongli.myapplication.common.callback.ResponseCallback;
import com.jshongli.myapplication.common.utils.AccountManager;
import com.jshongli.myapplication.common.utils.AppManager;
import com.jshongli.myapplication.common.utils.ParseUtils;
import com.jshongli.myapplication.common.utils.ToastUtils;
import com.jshongli.myapplication.common.utils.URLUtils;
import com.jshongli.myapplication.model.task.TaskBean;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Request;

public class TaskActivity extends BaseActivity {

    public static TaskActivity xActivity;

    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.recy)
    RecyclerView recy;
    @BindView(R.id.ll_btn)
    LinearLayout ll_btn;
    @BindView(R.id.et_search)
    EditText et_search;
    @BindView(R.id.tv_filter)
    TextView tv_filter;

    List<TaskBean.DATA> mData = new ArrayList<>();
    BaseQuickAdapter<TaskBean.DATA, BaseViewHolder> mAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_task;
    }

    @Override
    protected void initData() {
        super.initData();
        xActivity = this;
        tv_filter.setTag("");
    }

    @Override
    protected void initView() {
        super.initView();

        initToolbarBack(mToolbar);
        mToolbar.setTitle("我的任务");

        mRefreshLayout.setColorSchemeResources(R.color.refresh_blue,
                R.color.refresh_red, R.color.refresh_blue, R.color.refresh_red);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData();
            }
        });

        et_search.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    //先隐藏键盘
                    ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

                    //其次再做相应操作
                    getData();
                }
                return false;
            }
        });

        initPicker();

        getData();

    }

    OptionsPickerView pvFilter;
    private void initPicker(){
        List<String> list = new ArrayList<>();
        list.add("全部");
        list.add("待处理");
        list.add("处理中");
        list.add("处理完成");

        pvFilter = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                tv_filter.setText(list.get(options1));
                if(options1 == 0){
                    tv_filter.setTag("");
                }else {
                    tv_filter.setTag(options1-1);
                }

                getData();
            }
        }).build();
        pvFilter.setPicker(list);
    }
    //endregion

    //region HTTP -- 获取任务列表
    int page = 1;
    public void getData() {
        page = 1;
        String url = URLUtils.URLNoToken("manageAPI/bizWork/getPageList");
        Map<String, String> map = new HashMap<>();
        map.put("page", "1");
        map.put("limit", "20");

        map.put("title", et_search.getText().toString());
        map.put("status", tv_filter.getTag().toString());

        OkHttpUtils
                .get()
                .url(url)
                .addHeader("Authorization", AccountManager.getToken())
                .params(map)
                .tag(this)
                .build()
                .execute(new ResponseCallback<TaskBean>(mContext) {

                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                        mRefreshLayout.setRefreshing(true);
                    }

                    @Override
                    public void onAfter(int id) {
                        super.onAfter(id);
                        mRefreshLayout.setRefreshing(false);
                    }

                    @Override
                    public void onResponse(TaskBean response, int id) {
                        super.onResponse(response, id);
                        if (response.code == 0) {
                            if (response.data != null) {
                                mData = response.data;
                            }
                        }  else {
                            if(response.msg != null && "请登录后再访问接口".equals(response.msg))
                            {
                                AppManager.exceptionExitToLogin(mContext, response.msg);
                            }else {
                                ToastUtils.show(mContext, "查询出错");
                            }
                        }

                        if (mAdapter == null) {
                            initRecy();
                        } else {
                            mAdapter.setNewData(mData);
                        }
                    }


                });
    }

    private void loadMore() {
        page = page + 1;
        String url = URLUtils.URLNoToken("manageAPI/bizWork/getPageList");

        Map<String, String> map = new HashMap<>();
        map.put("page", page+"");
        map.put("limit", getResources().getString(R.string.limit));
        map.put("title", et_search.getText().toString());
        map.put("status", tv_filter.getTag().toString());

        OkHttpUtils
                .get()
                .url(url)
                .addHeader("Authorization", AccountManager.getToken())
                .params(map)
                .tag(this)
                .build()
                .execute(new ResponseCallback<TaskBean>(mContext) {
                    @Override
                    public void onResponse(TaskBean response, int id) {
                        super.onResponse(response, id);

                        if (response.code == 0) {
                            if (response.data.size() <= 0) {
                                mAdapter.loadMoreEnd();
                            } else {
                                mData.addAll(response.data);
                                mAdapter.loadMoreComplete();
                            }
                        } else {
                            mAdapter.loadMoreEnd();
                        }


                    }

                });

    }

    //endregion

    //region initRecy
    private void initRecy() {
        mAdapter = new BaseQuickAdapter<TaskBean.DATA, BaseViewHolder>(R.layout.list_task_item, mData) {
            @Override
            protected void convert(BaseViewHolder helper, TaskBean.DATA item) {

                helper.setText(R.id.tv_bh, item.title)
                        .setText(R.id.tv_zt, ParseUtils.wdrw_new_zt_txt(item.status))
                        .setText(R.id.tv_fqdw, item.createName)
                        .setText(R.id.tv_tm, item.createTime);

                helper.setBackgroundRes(R.id.tv_zt,ParseUtils.wdrw_new_zt_bg(item.status));


            }
        };

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                TaskBean.DATA item = mData.get(position);
                Bundle bundle = new Bundle();
                bundle.putSerializable("item", item);
                bundle.putInt("type", 0);
                openActivity(TaskDetailActivity.class, bundle, false);
//                openActivityForResult(TaskDetailActivity.class, bundle,000001);
            }
        });

        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        }, recy);

        View emptyView = LayoutInflater.from(mContext).inflate(R.layout.empty_view, null);
        mAdapter.setEmptyView(emptyView);

        recy.setAdapter(mAdapter);
        recy.setLayoutManager(new LinearLayoutManager(mContext));
    }
    //endregion

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode==000001){
//            //处理回调相关操作
//            mRefreshLayout.setRefreshing(true);
//            getData();
//        }
//    }


    @OnClick({R.id.ll_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_btn:
                pvFilter.show();
                break;
        }
    }
}